package com.zxt.utils;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ListUtils {
    /**
     * 按照份数---划分list
     *
     * @param source 目标源
     * @param num    划分份数
     * @return
     */
    public static <T> List<List<T>> splitListByNum(List<T> source, int num) {
        List<List<T>> result = new ArrayList<>();
        //(先计算出余数)
        int remaider = source.size() % num;
        //然后是商
        int number = source.size() / num;
        //偏移量
        int offset = 0;
        for (int i = 0; i < num; i++) {
            List<T> value = null;
            if (remaider > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remaider--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        //List<List<T>> partition = Lists.partition(source, 10);
        return result;
    }

    /**
     * 根据目标容量--划分List
     *
     * @param source   目标源
     * @param capacity 划分容量
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> splitListBycapacity(List<T> source, int capacity) {
        //判断集合是否为空
        if (ZXTCollectionsUtil.isEmpty(source)) {
            return Collections.emptyList();
        }
        //计算分割后的大小
        int maxSize = (source.size() + capacity - 1) / capacity;
        //开始分割
        return Stream.iterate(0, n -> n + 1)
                .limit(maxSize)
                .parallel()
                .map(a -> source.parallelStream().skip(a * capacity).limit(capacity).collect(Collectors.toList()))
                .filter(b -> !b.isEmpty())
                .collect(Collectors.toList());
    }


    public static void main(String[] args) {
        List<Integer> all = new ArrayList<>();
        int a = 1000;
        for (int i = 0; i < a; i++) {
            all.add(i + 1);
        }

        List<List<Integer>> split = splitListBycapacity(all, 300);
        System.out.println(split.size());
        for (List<Integer> strings : split) {
            System.out.println(strings.size());
        }
    }
}
